package lastcontrnt.memoryleak;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLeak {
    public  static void main(String[] args) throws Exception {

        ThreadLeak threadLeak = new ThreadLeak();
        int n = 300000;
        for (int i = 0; i < n; i++) {
            threadLeak.test2();
        }
    }

    public void test2() throws Exception{

        ThreadPoolExecutor executor = new ThreadPoolExecutor(10,20, 0L, TimeUnit.SECONDS,  new LinkedBlockingQueue<>(), new NamedThreadFactory("并发线程"));

        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        String jvmName = runtimeBean.getName();
        //System.out.println("JVM Name = " + jvmName);    long pid = Long.parseLong(jvmName.split("@")[0]);
        //System.out.println("JVM PID  = " + pid);
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();

        for(int j = 0; j<10; j++){
            executor.execute(()->{
                System.out.println("当前线程总数为："+bean.getThreadCount());
            });
        }
        //executor.shutdown();

        Thread.sleep(500);
        System.out.println("线程总数为 = " + bean.getThreadCount());
    }

    public class NamedThreadFactory implements ThreadFactory {

        private  AtomicInteger poolNumber = new AtomicInteger(1);

        private  ThreadGroup threadGroup;

        private  AtomicInteger threadNumber = new AtomicInteger(1);

        public   String namePrefix;

        NamedThreadFactory(String name){
            SecurityManager s = System.getSecurityManager();
            threadGroup = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            if (null==name || "".equals(name.trim())){
                name = "pool";
            }
            namePrefix = name +"-"+
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(threadGroup, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
